import java.util.*;

public class Solution2 {
    int m;
    int n;
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};

    public int cutOffTree(List<List<Integer>> forest) {
        m = forest.size();
        n = forest.get(0).size();
        // 1.准备工作：确定砍树顺序
        List<int[]> trees = new ArrayList<>();
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(forest.get(i).get(j) > 1) {
                    trees.add(new int[]{i, j});
                }
            }
        }
        Collections.sort(trees, (a, b) -> {
            return forest.get(a[0]).get(a[1]) - forest.get(b[0]).get(b[1]);
        });

        // 2. 按照顺序砍树
        int ret = 0;
        int bx = 0;
        int by = 0;
        for(int[] tree : trees) {
            int x = tree[0];
            int y = tree[1];
            int step = bfs(forest, bx, by, x, y);
            if(step == -1) {
                return -1;
            }
            ret += step;
            bx = x;
            by = y;
        }
        return ret;
    }

    public int bfs(List<List<Integer>> f, int bx, int by, int x, int y) {
        if(bx == x && by == y) {
            return 0;
        }
        Queue<int[]> q = new LinkedList<>();
        boolean[][] check = new boolean[m][n];
        q.add(new int[]{bx, by});
        check[bx][by] = true;
        int ret = 0;
        while(!q.isEmpty()) {
            ret++;
            int sz = q.size();
            for(int i = 0; i < sz; i++) {
                int[] t = q.poll();
                for(int k = 0; k < 4; k++) {
                    int a = t[0] + dx[k];
                    int b = t[1] + dy[k];
                    if(a >= 0 && a < m && b >= 0 && b < n && !check[a][b] && f.get(a).get(b) > 0) {
                        if(a == x && b == y) {
                            return ret;
                        }
                        q.add(new int[]{a, b});
                        check[a][b] = true;
                    }
                }
            }
        }
        return -1;
    }
}
